package server

import (
	"data_service/models"
	"encoding/json"
	"fmt"
	"log"
	"time"

	"github.com/gorilla/websocket"
	"gorm.io/gorm"
)

// ChatService 聊天服务
type ChatService struct {
	db *gorm.DB
}

// NewChatService 创建聊天服务实例
func NewChatService(db *gorm.DB) *ChatService {
	return &ChatService{db: db}
}

// WebSocketMessage WebSocket消息结构
type WebSocketMessage struct {
	Type      string      `json:"type"`
	Data      interface{} `json:"data"`
	Timestamp time.Time   `json:"timestamp"`
}

// ChatMessageRequest 聊天消息请求
type ChatMessageRequest struct {
	RoomID      string `json:"room_id" binding:"required"`
	Content     string `json:"content" binding:"required"`
	MessageType string `json:"message_type"`
}

// JoinRoomRequest 加入房间请求
type JoinRoomRequest struct {
	RoomID string `json:"room_id" binding:"required"`
}

// LeaveRoomRequest 离开房间请求
type LeaveRoomRequest struct {
	RoomID string `json:"room_id" binding:"required"`
}

// ChatMessageResponse 聊天消息响应
type ChatMessageResponse struct {
	ID          uint      `json:"id"`
	RoomID      string    `json:"room_id"`
	UserID      uint      `json:"user_id"`
	UserName    string    `json:"user_name"`
	Content     string    `json:"content"`
	MessageType string    `json:"message_type"`
	Timestamp   time.Time `json:"timestamp"`
}

// CreateChatMessage 创建聊天消息
func (s *ChatService) CreateChatMessage(message *models.ChatMessage) error {
	return s.db.Create(message).Error
}

// GetChatMessages 获取聊天消息
func (s *ChatService) GetChatMessages(roomID string, limit, offset int) ([]models.ChatMessage, error) {
	var messages []models.ChatMessage
	err := s.db.Where("room_id = ?", roomID).
		Order("timestamp DESC").
		Limit(limit).
		Offset(offset).
		Find(&messages).Error
	return messages, err
}

// CreateChatRoom 创建聊天房间
func (s *ChatService) CreateChatRoom(room *models.ChatRoom) error {
	return s.db.Create(room).Error
}

// GetChatRoom 获取聊天房间
func (s *ChatService) GetChatRoom(roomID string) (*models.ChatRoom, error) {
	var room models.ChatRoom
	err := s.db.Where("room_id = ? AND is_active = ?", roomID, true).First(&room).Error
	return &room, err
}

// AddOnlineUser 添加在线用户
func (s *ChatService) AddOnlineUser(user *models.OnlineUser) error {
	// 先删除该用户的其他连接
	s.db.Where("user_id = ?", user.UserID).Delete(&models.OnlineUser{})
	return s.db.Create(user).Error
}

// RemoveOnlineUser 移除在线用户
func (s *ChatService) RemoveOnlineUser(socketID string) error {
	return s.db.Where("socket_id = ?", socketID).Delete(&models.OnlineUser{}).Error
}

// GetOnlineUsers 获取在线用户列表
func (s *ChatService) GetOnlineUsers() ([]models.OnlineUser, error) {
	var users []models.OnlineUser
	err := s.db.Where("is_online = ?", true).Find(&users).Error
	return users, err
}

// GetOnlineUserBySocketID 根据SocketID获取在线用户
func (s *ChatService) GetOnlineUserBySocketID(socketID string) (*models.OnlineUser, error) {
	var user models.OnlineUser
	err := s.db.Where("socket_id = ?", socketID).First(&user).Error
	return &user, err
}

// UpdateUserLastSeen 更新用户最后在线时间
func (s *ChatService) UpdateUserLastSeen(userID uint) error {
	return s.db.Model(&models.OnlineUser{}).
		Where("user_id = ?", userID).
		Update("last_seen", time.Now()).Error
}

// GetUserByID 根据用户ID获取用户信息
func (s *ChatService) GetUserByID(userID uint) (*models.User, error) {
	var user models.User
	err := s.db.Where("id = ?", userID).First(&user).Error
	return &user, err
}

// GetUserByEmail 根据邮箱获取用户信息
func (s *ChatService) GetUserByEmail(email string) (*models.User, error) {
	var user models.User
	err := s.db.Where("email = ?", email).First(&user).Error
	return &user, err
}

// GetUserChatRooms 获取用户创建的活动房间
func (s *ChatService) GetUserChatRooms(userID uint) ([]models.ChatRoom, error) {
	var rooms []models.ChatRoom
	err := s.db.Where("created_by = ? AND is_active = ?", userID, true).
		Order("updated_at DESC").
		Find(&rooms).Error
	return rooms, err
}

// ParseWebSocketMessage 解析WebSocket消息
func (s *ChatService) ParseWebSocketMessage(data []byte) (*WebSocketMessage, error) {
	var message WebSocketMessage
	if err := json.Unmarshal(data, &message); err != nil {
		return nil, fmt.Errorf("解析消息失败: %v", err)
	}
	message.Timestamp = time.Now()
	return &message, nil
}

// CreateWebSocketResponse 创建WebSocket响应
func (s *ChatService) CreateWebSocketResponse(messageType string, data interface{}) *WebSocketMessage {
	return &WebSocketMessage{
		Type:      messageType,
		Data:      data,
		Timestamp: time.Now(),
	}
}

// SendWebSocketMessage 发送WebSocket消息
func (s *ChatService) SendWebSocketMessage(conn *websocket.Conn, message *WebSocketMessage) error {
	messageBytes, err := json.Marshal(message)
	if err != nil {
		return fmt.Errorf("序列化消息失败: %v", err)
	}

	if err := conn.WriteMessage(websocket.TextMessage, messageBytes); err != nil {
		return fmt.Errorf("发送消息失败: %v", err)
	}

	return nil
}

// LogChatActivity 记录聊天活动日志
func (s *ChatService) LogChatActivity(userID uint64, action, roomID string) {
	log.Printf("[CHAT] 用户ID: %d, 操作: %s, 房间: %s, 时间: %s",
		userID, action, roomID, time.Now().Format("2006-01-02 15:04:05"))
}
